/*
	Copyright (C) 2008 by Jean-FranÁois Geyelin
	jfgeyelin@gmail.com

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the
	Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "all.h"
#include "ThreadParameters.h"
#include "safeFileIO.h"
#include "constants.h"
#include "downloadFileFromServer.h"

#ifndef NO_LIBCURL
#ifndef __APPLE__
    #include <curl/curl.h>
    #include <curl/types.h>
    #include <curl/easy.h>
#endif
#endif

size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) {
    int written = fwrite(ptr, size, nmemb, (FILE *)stream);
    return written;
}




int getFileFromServerThread(void *parameters) {
#ifndef NO_LIBCURL
    ThreadParameters *tp = (ThreadParameters *)parameters;
    SDL_Delay(400);
	std::string userAgent = USER_AGENT;
#ifndef __APPLE__
	/*****************
	 LINUX & WIN code
	 ******************/
    FILE *f;
    f = fopen_safe(tp->getFilePath().c_str(),"wb");
    if (!f) {
        tp->setFileIsDownloaded(true);
        return 0;
    }


    CURL *curl;
    CURLcode res=res;
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, tp->getUrl().c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA , f);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    if (res!=0) {
        tp->setThereHasBeenAnError(true);
    }
	fclose(f);
#else
	/*****************
	 OS X code
	 ******************/
	std::string command;
	std::string fullFilePath = getFullPath(tp->getFilePath());
	command = "curl --user-agent "+userAgent+" --url "+tp->getUrl()+" >"+fullFilePath;
	system(command.c_str());


#endif




    tp->setFileIsDownloaded(true);
#endif
    return 0;
}
